<?php

class SiteController extends CController
{
	public $pageTitle='嗅交友社区：基于兴趣的单身交友平台，结识同好，找到你的臭（xiù）味相投';
	public $breadcrumbs;
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{

		if(!Yii::app()->user->isGuest)$this->redirect('?r=home');
		//获取最新注册的开放个人空间的用户
		$pops = User::model()->findAllBySql("select id,nickname,sex,birth,city_id,avatar from users where space_privacy=0 ORDER BY RAND() limit 8 ");

		$this->render('index',array('pops'=>$pops));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->renderPartial('error', $error);
		}
	}


	/**
	 * Displays the login page
	 */
	public function actionLogin(){
		// collect user input data
		if(Yii::app()->request->isAjaxRequest){
			$hasErrors=false;
			if(trim($_POST['username'])==''||trim($_POST['password'])==''){
				$hasErrors=true;
				$message = '用户名和密码不能为空';
			}
			// print_r($_POST);exit;
		if(!$hasErrors){
			$identity = new UserIdentity($_POST['username'],$_POST['password']);
			$identity->authenticate();

			switch ($identity->errorCode) {
                    case UserIdentity::ERROR_NONE:
                        $duration = $_POST['rememberMe'] ? 3600 * 24 * 1 : 0; // 1 day
                        Yii::app()->user->login($identity, $duration);
                        // $returnUrl = Yii::app()->user->returnUrl;
                        // echo($returnUrl);exit;
                        // if(substr($_SERVER['HTTP_REFERER'],0,5)=='https')
                        // {
                        //     $returnUrl = str_replace('http','https',$returnUrl);
                        // }
                        // $this->redirect($returnUrl);
                        $message='ok';
                        // return;
                        break;
                    case UserIdentity::ERROR_USERNAME_INVALID:
                        $message = '用户名错误！';
                        break;
                    default: // UserIdentity::ERROR_PASSWORD_INVALID
                        $message = '用户密码错误！';
                        break;
                }
		}
		echo $message;exit;
		}
		$this->redirect('?r=site');
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}


	public function actionRegist(){
		$user = new User('create');
		$setting= new UserSetting('create');
		$msg = array('status'=>0);
		if(Yii::app()->request->isAjaxRequest && $_POST['ajax']==='user-regist'){
			echo CActiveForm::validate($user);
        	Yii::app()->end();
		}
		if(isset($_POST['User'])&&isset($_POST['UserSetting']))
		{
			$user->attributes=$_POST['User'];
			$setting->attributes=$_POST['UserSetting'];
			$p= crypt($user->password);
			$user->password=crypt($user->password_tmp,$p);
			// print_r($_POST['User']);
			// echo($user->password);
			$transaction=Yii::app()->db->beginTransaction();
			try {
				if($user->save()){
					$setting->uid = $user->id;
					$setting->save();
					$msg['status']=0;
				}else{
					$msg['status']=1;
					// print_r($user->getErrors());
					// throw new Exception('用户信息注册失败');
				}
				$transaction->commit();
				if($msg['status']=='0'){

					//让用户登录
					$identity = new UserIdentity($user->email,$user->password_tmp);
					$identity->authenticate();
					$duration = $_POST['rememberMe'] ? 3600 * 24 * 1 : 0; // 1 day
                    if(Yii::app()->user->login($identity, $duration)){
                    	$posts = array(array('我的个性描述','这是我的个性描述'),array('我的生活习惯','这是我的生活习惯'),array('我的爱情观点','这是我的爱情观点'));

					foreach($posts as $v){
						$p = new Post('create');
						$p->subject = $v[0];
						$p->content = $v[1];
					
						$p->save();
						}
					$this->redirect(array('reg/avatar'));
                    }
						
				}
			} catch (Exception $e) {
				echo($e->getMessage());
				$transaction->rollBack();
			}
	
		}
		$this->render('regist',array('user'=>$user,'setting'=>$setting));
	}

	

	public function actionGenArea(){
		$rs = array_flip(Area::getArea());
		foreach($rs as $k=>$v){
			$citys = array_flip(Area::getArea($v));
			$tmp[$k] = array('key'=>$v,'values'=>$citys);
		}
		print_r($tmp);
		$str =json_encode($tmp);
		$str=preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $str);
		// echo $str;
	}
}